<?php 
namespace app\admin\controller;
use think\Controller;

class Brand extends Controller{
	public function index(){
		$data=db('brand')->order('id desc')->paginate(15);
		$this->assign([
			"data"		=>$data,
		]);
		return view();
	}

	public function add(){
		if(request()->isPost()){
			$data=input("post.");
			//给域名添加http:
			if($data['brand_url'] && stripos($data['brand_url'],"http://") === false){
				$data['brand_url'] = 'http://'.$data['brand_url'];
			}
			//图片处理
			if($_FILES['brand_image']['tmp_name']){
				$data['brand_image']=$this->upload();
			}
			// 数据验证
			$validate=validate('Brand');
			if(!$validate->check($data)){
				$this->error($validate->getError());
			}
			$datares=db('brand')->insert($data);
			if($datares){
				$this->success('添加品牌成功',url('index'));
			}else{
				$this->error('添加品牌失败！');
			}
		}
		return view();
	}

	public function edit($id){
		$brand=db('brand');		
		if(request()->isPost()){
			$data=input('post.');
			//给域名添加http
			if($data['brand_url'] && stripos($data['brand_url'],"http://") === false){
				$data['brand_url'] = 'http://'.$data['brand_url'];
			}
			//修改图片处理
			if($_FILES['brand_image']['tmp_name']){
				$oldimg=$brand->field('brand_image')->find($data['id']);
				$oldimgsrc=IMG_UPLOAD.$oldimg['brand_image'];
				if(file_exists($oldimgsrc)){
					@unlink($oldimgsrc);
				}
				$data['brand_image']=$this->upload();
			}
			$brandRes=$brand->update($data);
			if($brandRes!==false){
				$this->success('品牌修改成功！',url('index'));
			}else{
				$this->error('品牌修改失败！');
			}
		}
		$data=$brand->find($id);
		$this->assign([
			'data'		=>$data,
		]);
		return view();
	}

	public function del($id){
		$brand=db('brand');
		$data=$brand->find($id);
		if($data['brand_image']){
			@unlink(ROOT_PATH.'public/static/upload/'.$data['brand_image']);
		}
		$res=$brand->delete($id);
		if($res){
			$this->success('品牌删除成功！',url('index'));
		}else{
			$this->error('品牌删除失败！');
		}
	}

	public function upload(){
		$file=request()->file('brand_image');
		if($file){
			$info=$file->move(ROOT_PATH.'public'.DS.'static'.DS.'upload');
			if($info){
				return $info->getSaveName();
			}else{
				echo $file->getError();
				die;
			}
		}
	}

}